import Vue from "vue"
import VueRouter from "vue-router"
import { clearPending } from "api/config"
import propsal from "./propsal"
import member from "./member"
import socialPublic from "./socialPublic"
import memProposal from "./role_member/proposal"
import unitProposal from "./role_cb_unit/proposal"
import systemProposal from "./role_cb_system/proposal"
Vue.use(VueRouter)
const NotFound = () => import("../components/404/index")
const console = () => import("../views/console.vue")
const login = () => import("../views/login/login.vue")
const Home = () => import("../views/home.vue")
const resumeDetail = () =>
  import("../views/role_org/member/sessionMgt/resumeDetail.vue")
const proposalDetail = () =>
  import("../views/role_member/proposal/proposalDetail.vue")
const noticeDetail = () =>
  import("../views/role_member/proposal/notice/detail.vue")
const replyNotice = () =>
  import("../views/role_member/proposal/notice/reply.vue")
const routes = [
  { path: "/", redirect: "/console" },
  {
    path: "/console",
    name: "console",
    component: console,
    children: [
      ...propsal,
      ...member,
      ...socialPublic,
      ...memProposal,
      ...unitProposal,
      ...systemProposal,
      { path: "home", name: "首页", component: Home },
    ],
  },
  {
    path: "/login",
    name: "login",
    component: login,
  },
  {
    path: "/memberResume/detail",
    name: "委员履职详情",
    component: resumeDetail,
  },
  {
    path: "/cppccproposal/proposaldetail",
    name: "我的提案详情",
    component: proposalDetail,
  },
  {
    path: "/cppccproposal/replynotice",
    name: "回复通知",
    component: replyNotice,
  },
  {
    path: "/cppccproposal/noticedetail",
    name: "通知详情",
    component: noticeDetail,
  },
  { path: "*", component: NotFound },
]

const router = new VueRouter({
  mode: "hash",
  base: process.env.BASE_URL,
  routes,
})
// 策略模式，对重定向的路由标题进行修复
const redirect = {
  "/console": "主页",
}
const special = {
  "/login": "登录",
}
// 添加后置路由
router.afterEach((to) => {
  let { path } = to
  const title = special[path]
  if (title) {
    document.title = title
    return
  }
  path = redirect[path] || path
  // 简单深拷贝一下数组，递归寻找一下标题
  const arr = routes
  while (arr.length) {
    const child = arr.pop()
    if (path === child.name) {
      document.title = child.text
      break
    }
    if (Array.isArray(child.children)) {
      arr.push(...child.children)
    }
  }
})
//添加前置路由
router.beforeEach((to, from, next) => {
  //路由拦截,重定向
  // 1. 判断访问的是不是登录 页面
  clearPending() //清除pending
  if (to.path === "/login") {
    next()
  } else {
    if (localStorage.getItem("TOKEN")) {
      next()
    } else {
      next("/login")
    }
  }
})
export default router
